import { createRouter, createWebHashHistory } from 'vue-router'
import store from '@/store';

import Home from "../views/Home.vue";
import Login from "../views/Login.vue";
import FoodDetail from "../views/FoodDetail.vue";

import Order from "@/views/Order.vue";
import ChooseFood from "@/views/ChooseFood.vue";
import Category from "@/views/Category.vue";
import My from "@/views/My.vue";
import Register from "../views/Register.vue";
import ShopCartList from "../views/ShopCartList.vue"
import AddressInfoList from "../views/AddressInfoList.vue"
import AddAddressInfo from "../views/AddAddressInfo.vue"
import EditAddress from "../views/EditAddress.vue"

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: "/",
      redirect: {
        name: "ChooseFood"
      }
    },
    {
      path: "/Home",
      name: "Home",
      component: Home,
      children: [
        {
          path: "Order",
          name: "Order",
          component: Order
        },
        {
          path: "ChooseFood",
          name: "ChooseFood",
          component: ChooseFood
        },
        {
          path: "Category",
          name: "Category",
          component: Category
        },
        {
          path: "My",
          name: "My",
          component: My
        },
      ]
    },
    {
      path: "/Login",
      name: "Login",
      component: Login
    },
    {
      path: "/FoodDetail/:id",
      name: "FoodDetail",
      component: FoodDetail
    },
    {
      path: "/Register",
      name: "Register",
      component: Register
    },
    {
      path: "/ShopCartList",
      name: "ShopCartList",
      component: ShopCartList,
      // 通过meta标记附加了网页的基本信息
      // 同时注意requireAuth， 假设登陆以后才能访问的网页
      meta: {
        requireAuth: true
      }
    },
    {
      path: "/AddressInfoList",
      name: "AddressInfoList",
      component: AddressInfoList,
      meta: {
        requireAuth: true
      }
    },
    {
      path: "/AddAddressInfo",
      name: "AddAddressInfo",
      component: AddAddressInfo,
      meta: {
        requireAuth: true
      }
    },
    {
      path: "/EditAddress/:id",
      name: "EditAddress",
      component: EditAddress,
      meta: {
        requireAuth: true
      }
    },
  ]
})
// 导航守卫
router.beforeEach((to, from, next) => {
  // to代表去哪里，from代表从哪来，next代表放行
  if (to.meta.requireAuth === true) {
    // 说明你要去的页面需要登录
    if(store.getters.loginUserInfo){
      // 说明登录了，放行
      next();
    }
    else{
      // 没有登录,下一个页面为登录页面
      next({
        name:"Login"
      })
    }
  }
  else {
    // 说明去的页面不需要登录
    next();
  }
})

// 后置守卫
// router.afterEach((to,from)=>{

// })

export default router
